package cn.z2huo.knowledge.java.base.java.lang.management;

import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * <p>
 *
 * @author z2huo
 */
class ManagementFactoryTest {

    private static OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();

    public static void main(String[] args) {

        double loadAverage = osBean.getSystemLoadAverage();
        System.out.println("loadAverage: " + loadAverage);
        System.out.println();

        double cpuUsage = getCpuUsage();
        System.out.println("cpuUsage: " + cpuUsage);
        System.out.println();

        double memoryUsage = getMemoryUsage();
        System.out.println("memoryUsage: " + memoryUsage);
    }

    private static double getCpuUsage() {
        try {
            Method method = osBean.getClass().getMethod("getSystemCpuLoad");
            double cpuUsage = (double) method.invoke(osBean);
            return cpuUsage;
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    private static double getMemoryUsage() {
        long totalMemory = Runtime.getRuntime().totalMemory();
        long freeMemory = Runtime.getRuntime().freeMemory();
        long maxMemory = Runtime.getRuntime().maxMemory();
        double memoryUsage = (double) (totalMemory - freeMemory) / totalMemory * 100;
        return memoryUsage;
    }

}
